﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing;

namespace MortEdit
{
    // Klasa odpowiedzialna za wspomaganie RichTextBoxExtended
    internal class RichTextBoxExtendedHelper
    {
        [DllImport("user32.dll")]
        public static extern int GetCaretPos(ref Point lpPoint);

        private static int GetCorrection(RichTextBox richTextBox, int index)
        {
            Point pt1 = Point.Empty;
            GetCaretPos(ref pt1);
            Point pt2 = richTextBox.GetPositionFromCharIndex(index);

            if (pt1 != pt2)
                return 1;
            else
                return 0;
        }

        public static int CurrentLine(RichTextBox richTextBox, int index)
        {
            int correction = GetCorrection(richTextBox, index);
            return richTextBox.GetLineFromCharIndex(index) - correction + 1;
        }

        public static int CurrentColumn(RichTextBox richTextBox, int index1)
        {
            int correction = GetCorrection(richTextBox, index1);
            Point p = richTextBox.GetPositionFromCharIndex(index1 - correction);

            if (p.X == 1)
                return 1;

            p.X = 0;
            int index2 = richTextBox.GetCharIndexFromPosition(p);

            int col = index1 - index2 + 1;

            return col;
        }

        public static int CurrentLineStartIndex(RichTextBox richTextBox)
        {
            return richTextBox.GetFirstCharIndexOfCurrentLine();
        }

        public static string CurrentLineText(RichTextBox richTextbox)
        {
            int charIndex = richTextbox.SelectionStart;
            int currentLineNumber = richTextbox.GetLineFromCharIndex(charIndex);

            if (currentLineNumber < richTextbox.Lines.Length)
            {
                return richTextbox.Lines[currentLineNumber];
            }
            else
            {
                return string.Empty;
            }
        }

        public static string LastLineText(RichTextBox richTextbox)
        {
            int charIndex = richTextbox.SelectionStart;
            int currentLineNumber = richTextbox.GetLineFromCharIndex(charIndex);

            // the carriage return hasn't happened yet... 
            //      so the 'previous' line is the current one.
            string previousLineText;
            if (richTextbox.Lines.Length <= currentLineNumber)
                previousLineText = richTextbox.Lines[richTextbox.Lines.Length - 1];
            else
                previousLineText = richTextbox.Lines[currentLineNumber];

            return previousLineText;
        }
    }
}
